package com.ibeeking.found.msg.rest.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ibeeking.found.common.entity.MsgBaseCodeDTO;
import com.ibeeking.found.common.enums.PublishStatusEnum;

import com.ibeeking.found.common.enums.msg.MsgTemplateTypeEnum;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.gmc.global.api.feign.GlobalMsgBaseCodeFeignClient;

import com.ibeeking.gmc.global.api.common.query.MsgBaseCodeFeignQuery;
import com.ibeeking.found.msg.rest.service.*;
import com.ibeeking.found.msg.service.common.bo.MsgBindConfigBO;
import com.ibeeking.found.msg.service.common.dos.MsgBindConfigDO;
import com.ibeeking.found.msg.service.common.param.MsgBindConfigParam;
import com.ibeeking.found.msg.service.common.query.MsgBindConfigBaseQuery;
import com.ibeeking.found.msg.service.common.query.MsgBindConfigQuery;

import com.ibeeking.found.msg.service.common.vo.*;
import com.ibeeking.found.msg.service.mapper.MsgBindConfigMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseCodeEnum;
import com.ibeeking.nematos.utils.result.ResponseResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName MsgBindConfigServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2022-01-06 14:15
 **/
@Service
public class MsgBindConfigServiceImpl extends ServiceImpl<MsgBindConfigMapper, MsgBindConfigDO> implements IMsgBindConfigService {

    @Resource
    private MsgBindConfigMapper msgBindConfigMapper;
    @Resource
    private IWxMaMsgTemplateService wxMaMsgTemplateServiceImpl;
    @Resource
    private IEmailTemplateService emailTemplateServiceImpl;
    @Resource
    private ISysMsgTemplateService sysMsgTemplateServiceImpl;
    @Resource
    private ISmsTemplateService smsTemplateServiceImpl;
    @Resource
    private GlobalMsgBaseCodeFeignClient globalMsgBaseCodeFeignClient;
    @Resource
    private IWxCpMsgTemplateService wxCpMsgTemplateServiceImpl;
    @Resource
    private IWxMpMsgTemplateService wxMpMsgTemplateServiceImpl;
    @Resource
    private IWxMpSourceService mpSourceServiceImpl;


    @Override
    public List<MsgBindConfigBO> listBase(MsgBindConfigBaseQuery query) {
        List<MsgBindConfigDO> msgBindConfigDOS = msgBindConfigMapper.selectList(new LambdaQueryWrapper<MsgBindConfigDO>()
                .in(Collections3.isNotEmpty(query.getIds()), MsgBindConfigDO::getId, query.getIds())
        );
        return JsonUtils.jsonToList(msgBindConfigDOS, MsgBindConfigBO.class);
    }


    @Override
    public List<MsgBindConfigVO> list(MsgBindConfigQuery query) {
        MsgBaseCodeFeignQuery msgBaseCodeFeignQuery = BeanUtil.convertBean(query, MsgBaseCodeFeignQuery.class);
        ResponseResult<List<MsgBaseCodeDTO>> responseResult = globalMsgBaseCodeFeignClient.queryMsgBaseInfoList(msgBaseCodeFeignQuery);
        DataUtils.trueThrowException(!ResponseCodeEnum.SUCCESS.getCode().equals(responseResult.getCode()), "查询消息基本信息异常!");
        List<MsgBaseCodeDTO> msgBaseInfoList = responseResult.getData();
        DataUtils.trueThrowException(Collections3.isEmpty(msgBaseInfoList), "系统尚未添加消息基本信息!");
        List<Long> ids = msgBaseInfoList.stream().map(MsgBaseCodeDTO::getId).collect(Collectors.toList());
        List<MsgBindConfigBO> msgBindConfigBOS = getBean().listBase(new MsgBindConfigBaseQuery().setIds(ids));
        Map<Long, MsgBindConfigBO> msgBaseInfoConfigBOMap = msgBindConfigBOS.stream().collect(Collectors.toMap(MsgBindConfigBO::getId, x -> x, (o, n) -> n));
        List<MsgBindConfigVO> msgBindConfigVOS = JsonUtils.jsonToList(msgBaseInfoList, MsgBindConfigVO.class);
        for (MsgBindConfigVO msgBindConfigVO : msgBindConfigVOS) {
            MsgBindConfigBO msgBindConfigBO = msgBaseInfoConfigBOMap.get(msgBindConfigVO.getId());
            if (msgBindConfigBO != null) {
                cn.hutool.core.bean.BeanUtil.copyProperties(msgBindConfigBO, msgBindConfigVO);
            } else {
                msgBindConfigVO.setMaMsgEnable(PublishStatusEnum.DISABLE.getValue());
                msgBindConfigVO.setMpMsgMediaEnable(PublishStatusEnum.DISABLE.getValue());
                msgBindConfigVO.setMpMsgEnable(PublishStatusEnum.DISABLE.getValue());
                msgBindConfigVO.setCpMsgEnable(PublishStatusEnum.DISABLE.getValue());
                msgBindConfigVO.setSmsMsgEnable(PublishStatusEnum.DISABLE.getValue());
                msgBindConfigVO.setSysMsgEnable(PublishStatusEnum.DISABLE.getValue());
                msgBindConfigVO.setEmailMsgEnable(PublishStatusEnum.DISABLE.getValue());
            }
        }
        return msgBindConfigVOS;
    }

    @Override
    public List<MsgBindConfigVO> listByTemplateType(Integer templateType, String templateCode) {
        LambdaQueryWrapper<MsgBindConfigDO> queryWrapper = new LambdaQueryWrapper<>();
       if(templateType == MsgTemplateTypeEnum.MSG_TEMPLATE_EMAIL.getCode()) {
           queryWrapper.eq(StringUtils.isNotBlank(templateCode),MsgBindConfigDO::getEmailMsgTemplateCode,templateCode);
       }else if(templateType == MsgTemplateTypeEnum.MSG_TEMPLATE_SMS.getCode()) {
           queryWrapper.eq(StringUtils.isNotBlank(templateCode),MsgBindConfigDO::getSmsMsgTemplateCode,templateCode);
       }else if(templateType == MsgTemplateTypeEnum.MSG_TEMPLATE_SYS.getCode()) {
           queryWrapper.eq(StringUtils.isNotBlank(templateCode),MsgBindConfigDO::getSysMsgTemplateCode,templateCode);
       }else if(templateType == MsgTemplateTypeEnum.MSG_TEMPLATE_WX_CP.getCode()) {
           queryWrapper.eq(StringUtils.isNotBlank(templateCode),MsgBindConfigDO::getCpMsgTemplateCode,templateCode);
       }else if(templateType == MsgTemplateTypeEnum.MSG_TEMPLATE_WX_MP_TEXT.getCode()) {
           queryWrapper.eq(StringUtils.isNotBlank(templateCode),MsgBindConfigDO::getMpMsgTemplateCode,templateCode);
       }else if(templateType == MsgTemplateTypeEnum.MSG_TEMPLATE_WX_MA_SUBSCRIP.getCode()) {
           queryWrapper.eq(StringUtils.isNotBlank(templateCode),MsgBindConfigDO::getMaMsgTemplateCode,templateCode);
       }else if(templateType == MsgTemplateTypeEnum.MSG_TEMPLATE_WX_MP_MEDIA.getCode()) {
           queryWrapper.eq(StringUtils.isNotBlank(templateCode),MsgBindConfigDO::getMpMsgMediaTemplateCode,templateCode);
       }
         List<MsgBindConfigDO> msgBindConfigDOS = msgBindConfigMapper.selectList(queryWrapper);
        return JsonUtils.jsonToList(msgBindConfigDOS, MsgBindConfigVO.class);
    }
    /**
     * 根据code查询消息基本信息
     *
     * @param id
     * @return
     */
    @Override
    public MsgBindConfigViewVO view(Long id) {
        ResponseResult<MsgBaseCodeDTO> responseResult = globalMsgBaseCodeFeignClient.queryMsgBaseCodeDtoById(id);
        DataUtils.trueThrowException(!ResponseCodeEnum.SUCCESS.getCode().equals(responseResult.getCode()), "查询消息基本信息异常!");
        MsgBaseCodeDTO msgBaseCodeDTO = responseResult.getData();
        return getBean().viewBase(msgBaseCodeDTO);
    }

    /**
     * 根据code查询消息基本信息
     *
     * @param code
     * @return
     */
    @Override
    public MsgBindConfigViewVO viewByCode(String code) {
        ResponseResult<MsgBaseCodeDTO> responseResult = globalMsgBaseCodeFeignClient.queryMsgBaseCodeDtoByCode(code);
        DataUtils.trueThrowException(!ResponseCodeEnum.SUCCESS.getCode().equals(responseResult.getCode()), "查询消息基本信息异常!");
        MsgBaseCodeDTO msgBaseCodeDTO = responseResult.getData();
        if (ObjectUtil.isNull(msgBaseCodeDTO)) {
            throw new BusinessException("查询消息基本信息异常 返回值为空 code:" + code);
        }
        return getBean().viewBase(msgBaseCodeDTO);
    }

    @Override
    public MsgBindConfigViewVO viewBase(MsgBaseCodeDTO msgBaseCodeDTO) {
        Long msgBaseInfoId = msgBaseCodeDTO.getId();
        MsgBindConfigViewVO configViewVO = BeanUtil.convertBean(msgBaseCodeDTO, MsgBindConfigViewVO.class);
        MsgBindConfigBO msgBindConfigBO = getBean().selById(msgBaseInfoId);
        if (ObjectUtil.isNotNull(msgBindConfigBO)) {
            cn.hutool.core.bean.BeanUtil.copyProperties(msgBindConfigBO, configViewVO);
        } else {
            configViewVO.setMaMsgEnable(PublishStatusEnum.DISABLE.getValue());
            configViewVO.setMpMsgMediaEnable(PublishStatusEnum.DISABLE.getValue());
            configViewVO.setMpMsgEnable(PublishStatusEnum.DISABLE.getValue());
            configViewVO.setCpMsgEnable(PublishStatusEnum.DISABLE.getValue());
            configViewVO.setSmsMsgEnable(PublishStatusEnum.DISABLE.getValue());
            configViewVO.setSysMsgEnable(PublishStatusEnum.DISABLE.getValue());
            configViewVO.setEmailMsgEnable(PublishStatusEnum.DISABLE.getValue());
        }
        if (StringUtils.isNotBlank(configViewVO.getMaMsgTemplateCode())) {
            // 如果小程序订阅消息模板id不为空
            String templateCode = configViewVO.getMaMsgTemplateCode();
            WxMaMsgTemplateVO wxMaMsgTemplateVO = wxMaMsgTemplateServiceImpl.queryTemplateByCode(templateCode);
            configViewVO.setMaMsgTemplate(wxMaMsgTemplateVO);
        }
        if (StringUtils.isNotBlank(configViewVO.getSmsMsgTemplateCode())) {
            // 如果短信消息模板id不为空
            String templateCode = configViewVO.getSmsMsgTemplateCode();
            SmsTemplateVO smsTemplateVO = smsTemplateServiceImpl.queryTemplateByCode(templateCode);
            configViewVO.setSmsMsgTemplate(smsTemplateVO);
        }
        if (StringUtils.isNotBlank(configViewVO.getMpMsgTemplateCode())) {
            // 如果公众号模板消息模板id不为空
            String templateCode = configViewVO.getMpMsgTemplateCode();
            WxMpMsgTemplateVO wxMpMsgTemplateVO = wxMpMsgTemplateServiceImpl.queryTemplateByCode(templateCode);
            configViewVO.setMpMsgTemplate(wxMpMsgTemplateVO);
        }
        if (StringUtils.isNotBlank(configViewVO.getMpMsgMediaTemplateCode())) {
            // 如果公众号图文消息模板id不为空
            String templateCode = configViewVO.getMpMsgMediaTemplateCode();
            WxMpSourceSimpleVO wxMpSourceSimpleVO = mpSourceServiceImpl.sourceSimpleDtoView(Long.valueOf(templateCode));
            configViewVO.setMpMsgMediaTemplate(wxMpSourceSimpleVO);
        }
        if (StringUtils.isNotBlank(configViewVO.getEmailMsgTemplateCode())) {
            // 如果邮件消息模板id不为空
            String templateCode = configViewVO.getEmailMsgTemplateCode();
            EmailTemplateVO emailTemplateVO = emailTemplateServiceImpl.queryTemplateByCode(templateCode);
            configViewVO.setEmailMsgTemplate(emailTemplateVO);
        }
        if (StringUtils.isNotBlank(configViewVO.getSysMsgTemplateCode())) {
            // 如果邮件消息模板id不为空
            String templateCode = configViewVO.getSysMsgTemplateCode();
            SysMsgTemplateVO sysMsgTemplateVO = sysMsgTemplateServiceImpl.viewByCode(templateCode);
            configViewVO.setSysMsgTemplate(sysMsgTemplateVO);
        }
        if (StringUtils.isNotBlank(configViewVO.getCpMsgTemplateCode())) {
            // 如果企业微信消息模板id不为空
            String templateCode = configViewVO.getCpMsgTemplateCode();
            WxCpMsgTemplateVO wxCpMsgTemplateVO = wxCpMsgTemplateServiceImpl.queryTemplateByCode(templateCode);
            configViewVO.setWxCpMsgTemplate(wxCpMsgTemplateVO);
        }
        return configViewVO;
    }


    @Override
    public MsgBindConfigBO selById(Long id) {
        MsgBindConfigDO msgBindConfigDO = msgBindConfigMapper.selectById(id);
        return BeanUtil.convertBean(msgBindConfigDO, MsgBindConfigBO.class);
    }

    @Override
    public Boolean save(MsgBindConfigParam param) {
        Long id = param.getId();
        Long userId = UserUtils.getUserId();
        queryMsgBaseInfoDtoById(id);
        DataUtils.trueThrowException(PublishStatusEnum.ENABLE.getValue().equals(param.getMaMsgEnable()) && StringUtils.isBlank(param.getMaMsgTemplateCode()), "请选择小程序订阅消息!");
        DataUtils.trueThrowException(PublishStatusEnum.ENABLE.getValue().equals(param.getMpMsgEnable()) && StringUtils.isBlank(param.getMpMsgTemplateCode()), "请选择公众号模板消息!");
        DataUtils.trueThrowException(PublishStatusEnum.ENABLE.getValue().equals(param.getMpMsgMediaEnable()) && StringUtils.isBlank(param.getMpMsgMediaTemplateCode()), "请选择公众号图文消息!");
        DataUtils.trueThrowException(PublishStatusEnum.ENABLE.getValue().equals(param.getCpMsgEnable()) && StringUtils.isBlank(param.getCpMsgTemplateCode()), "请选择企业微信消息!");
        DataUtils.trueThrowException(PublishStatusEnum.ENABLE.getValue().equals(param.getSmsMsgEnable()) && StringUtils.isBlank(param.getSmsMsgTemplateCode()), "请选择短信消息!");
        DataUtils.trueThrowException(PublishStatusEnum.ENABLE.getValue().equals(param.getSysMsgEnable()) && StringUtils.isBlank(param.getSysMsgTemplateCode()), "请选择系统内消息!");
        DataUtils.trueThrowException(PublishStatusEnum.ENABLE.getValue().equals(param.getEmailMsgEnable()) && StringUtils.isBlank(param.getEmailMsgTemplateCode()), "请选择邮件消息!");

        MsgBindConfigBO msgBindConfigBO = getBean().selById(id);
        if (msgBindConfigBO == null) {
            //之前没配置过消息
            MsgBindConfigDO msgBindConfigDO = BeanUtil.convertBean(param, MsgBindConfigDO.class);
            msgBindConfigDO.setCreateBy(userId);
            msgBindConfigDO.setCreateTime(LocalDateTime.now());
            msgBindConfigDO.setModifyTime(LocalDateTime.now());
            msgBindConfigMapper.insert(msgBindConfigDO);
        } else {
            //之前配置过消息
            MsgBindConfigDO msgBindConfigDO = BeanUtil.convertBean(param, MsgBindConfigDO.class);
            msgBindConfigDO.setModifyBy(userId);
            msgBindConfigDO.setModifyTime(LocalDateTime.now());
            msgBindConfigMapper.updateById(msgBindConfigDO);
        }
        return true;
    }

    @Override
    public Boolean changeStatus(Long id, Integer type, Integer status) {
        MsgBindConfigDO msgBindConfigDO = msgBindConfigMapper.selectById(id);
        DataUtils.trueThrowException(msgBindConfigDO == null, "请先配置消息模板!");
        if(type == MsgTemplateTypeEnum.MSG_TEMPLATE_WX_MA_SUBSCRIP.getCode()){
            if(StringUtils.isBlank(msgBindConfigDO.getMaMsgTemplateCode())){
                throw new BusinessException("请先配置消息模板!");
            }
            msgBindConfigDO.setMaMsgEnable(status);
        } else if (type == MsgTemplateTypeEnum.MSG_TEMPLATE_WX_CP.getCode()) {
            if(StringUtils.isBlank(msgBindConfigDO.getCpMsgTemplateCode())){
                throw new BusinessException("请先配置消息模板!");
            }
            msgBindConfigDO.setCpMsgEnable(status);
        }else if(type == MsgTemplateTypeEnum.MSG_TEMPLATE_EMAIL.getCode()){
            if(StringUtils.isBlank(msgBindConfigDO.getEmailMsgTemplateCode())){
                throw new BusinessException("请先配置消息模板!");
            }
            msgBindConfigDO.setEmailMsgEnable(status);
        }else if(type == MsgTemplateTypeEnum.MSG_TEMPLATE_SMS.getCode()){
            if(StringUtils.isBlank(msgBindConfigDO.getSmsMsgTemplateCode())){
                throw new BusinessException("请先配置消息模板!");
            }
            msgBindConfigDO.setSmsMsgEnable(status);
        }else if(type == MsgTemplateTypeEnum.MSG_TEMPLATE_SYS.getCode()){
            if(StringUtils.isBlank(msgBindConfigDO.getSysMsgTemplateCode())){
                throw new BusinessException("请先配置消息模板!");
            }
            msgBindConfigDO.setSysMsgEnable(status);
        }else if(type == MsgTemplateTypeEnum.MSG_TEMPLATE_WX_MP_MEDIA.getCode()){
            if(StringUtils.isBlank(msgBindConfigDO.getMpMsgMediaTemplateCode())){
                throw new BusinessException("请先配置消息模板!");
            }
            msgBindConfigDO.setMpMsgMediaEnable(status);
        }else if(type == MsgTemplateTypeEnum.MSG_TEMPLATE_WX_MP_TEXT.getCode()){
            if(StringUtils.isBlank(msgBindConfigDO.getMpMsgTemplateCode())){
                throw new BusinessException("请先配置消息模板!");
            }
            msgBindConfigDO.setMpMsgEnable(status);
        }
        msgBindConfigDO.setModifyBy(UserUtils.getUserId());
        msgBindConfigDO.setModifyTime(LocalDateTime.now());
        return msgBindConfigMapper.updateById(msgBindConfigDO) >0;
    }

    /**
     * 从全局端查询消息基本信息
     *
     * @param id
     * @return
     */
    public MsgBaseCodeDTO queryMsgBaseInfoDtoById(Long id) {
        ResponseResult<MsgBaseCodeDTO> responseResult = globalMsgBaseCodeFeignClient.queryMsgBaseCodeDtoById(id);
        DataUtils.trueThrowException(!ResponseCodeEnum.SUCCESS.getCode().equals(responseResult.getCode()), "查询消息基本信息异常!");
        MsgBaseCodeDTO msgBaseCodeDTO = responseResult.getData();
        DataUtils.trueThrowException(msgBaseCodeDTO == null, "当前消息已失效,请刷新!");
        return msgBaseCodeDTO;
    }

    public IMsgBindConfigService getBean() {
        return SpringBeanUtil.getBean(IMsgBindConfigService.class);
    }
}
